package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Api(tags = "帖子接口")
@RestController
@Slf4j
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;
    @Autowired
    private IBoardService boardService;

    /**
     * 发布新帖子
     * @param boardId  板块id
     * @param title  标题
     * @param content 内容
     */
    @ApiOperation("发布新帖子")
    @PostMapping("/create")
    public AppResult createArticle(HttpServletRequest request,
                                   @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                                   @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                                   @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        //检验用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("用户已被禁言!");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }

        //封装文章对象
        Board board = boardService.selectById(boardId);
        if(null==board || board.getDeleteState() ==1 || board.getState() ==1 ){
            log.warn("当前板块异常!");
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        articleService.create(article);

        return AppResult.success();
    }

    /**
     * 获取帖子列表
     * @param boardId  板块id
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllBoardId")
    public AppResult<List<Article>> getAllBoardId(
            @ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId){
        List<Article> articleList;
        if (null==boardId){
            //查询所有
             articleList= articleService.selectAll();
        }else {
            articleList = articleService.selectAllByBoardId(boardId);
        }
        if(null == articleList){
            //没有查到
            articleList = new ArrayList<>();
        }

        //响应
        return AppResult.success(articleList);
    }

    /**
     * 根据帖子id查询详情,返回帖子详情
     * @param id 帖子id
     */
    @ApiOperation("返回帖子详情")
    @GetMapping("/details")
    private AppResult<Article> getDetail(HttpServletRequest request,
                                         @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        Article article = articleService.selectDetailById(id);
        if(null == article){
            log.error("找不到对应帖子!");
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST);
        }
        //判断当前用户是否是作者
        if(Objects.equals(user.getId(), article.getUserId())){
            //标识为作者
            article.setOwn(true);
        }
        //返回结果
        return AppResult.success(article);
    }


    /**
     * 修改帖子内容
     * @param id 帖子id
     * @param title 帖子标题
     * @param content 帖子正文
     */
    @ApiOperation("修改帖子内容")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam("content") @NonNull String content){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户信息
        if(user.getState()==1){
            log.warn("该用户已被禁言!,userId:{}",user.getId());
             return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子信息
        Article article = articleService.selectById(id);
        if(null == article){
            log.error("当前帖子不存在! articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST));
        }
        //判断用户是否是作者
        if(!Objects.equals(user.getId(), article.getUserId())){
            log.error("当前帖子作者不是改登录用户!该用户无权限更新");
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        //判断帖子状态
        if(article.getState()==1 || article.getDeleteState()==1){
            log.error("该帖子已无法被修改!");
            return AppResult.failed(ResultCode.ARTICLE_IS_BANNED);
        }
        //修改
        articleService.modify(id,title,content);
        log.info("帖子更新成功! articleId:{},userId:{}",id,user.getId());
        return AppResult.success();
    }

    /**
     * 点赞帖子内容
     * @param id 帖子id
     */
    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam("'帖子id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            log.warn("当前用户已被禁言!无法点赞,userId:{}",user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        log.info("当前用户点赞成功!userId:{}",user.getId());
        return AppResult.success();
    }

    /**
     * 删除帖子
     * @param id 帖子id
     */
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState()==1){
            //表示用户禁言
            log.warn("当前用户已被禁言!无法点赞,userId:{}",user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        if(null==article || article.getDeleteState()==1){
            //帖子已被删除
            log.warn("当前帖子不存在!");
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST);
        }
        if(!Objects.equals(article.getUserId(), user.getId())){
            //当前用户不是作者
            log.warn("当前用户没有操作权限!");
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        }
        articleService.deleteById(id);
        //操作成功进行返回
        return AppResult.success();
    }


    /**
     * 根据用户Id查询帖子列表
     * @param userId
     */
    @ApiOperation("根据用户Id查询帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId){
        //userId == null
        if(null==userId){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articleList = articleService.selectByUserId(userId);

        return AppResult.success(articleList);
    }
}
